<?php

namespace backend\controllers;

use Yii;
use common\models\fenhuicat\Fenhuicat;
use common\models\fenhuigrade\Fenhuigrade;
use common\models\fenhuicat\FenhuicatSearch;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\adminlog\AdminLog;
use yii\helpers\Html;

/**
 * FenhuicatController implements the CRUD actions for Fenhuicat model.
 */
class FenhuicatController extends Controller
{


    /**
     * Lists all Fenhuicat models.
     * @return mixed
     */
    public function actionIndex()
    {
        $grade = Yii::$app->db->createCommand('SELECT id,name FROM fenhuigrade where status = 10')->queryAll();

        $data = Yii::$app->db->createCommand('SELECT fenhuicat.* , fenhuigrade.name as title  FROM fenhuicat  left join fenhuigrade  on fenhuicat.fg_id = fenhuigrade.id  where fenhuicat.parent_id = 0')
            ->queryAll();
//print_r($data);exit;
//        $data = Fenhuicat::find()->where(['parent_id'=>0])->all();
        $id = 0;
        return $this->render('index', [
            'num' => count($data),
            'data' => $data,
            'grade' => $grade,
            'fg_id' => $id,
        ]);
    }

    /**
     * Lists all Fenhuicat models.
     * 筛选分会栏目
     * @return mixed
     */
    public function actionFg($id)
    {

        $grade = Yii::$app->db->createCommand('SELECT id,name FROM fenhuigrade where status = 10')->queryAll();
        if($id!=0) {
            $data = Yii::$app->db->createCommand("SELECT fenhuicat.* , fenhuigrade.name as title  FROM fenhuicat  left join fenhuigrade  on fenhuicat.fg_id = fenhuigrade.id  where fenhuicat.parent_id = 0 and fg_id = $id")
                ->queryAll();
        }else{
            $data = Yii::$app->db->createCommand("SELECT fenhuicat.* , fenhuigrade.name as title  FROM fenhuicat  left join fenhuigrade  on fenhuicat.fg_id = fenhuigrade.id  where fenhuicat.parent_id = 0 ")
                ->queryAll();
        }
//print_r($data);exit;
//        $data = Fenhuicat::find()->where(['parent_id'=>0])->all();
//        print_r($data);exit;
        return $this->render('index', [
            'num' => count($data),
            'data' => $data,
            'grade' => $grade,
            'fg_id' => $id,
        ]);
    }
    /**
     * Displays a single Fenhuicat model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {

        $data=Yii::$app->db->createCommand("SELECT fenhuicat.* , fenhuigrade.name as fname  FROM fenhuicat  left join fenhuigrade  on fenhuicat.fg_id = fenhuigrade.id  where fenhuicat.id = $id")
            ->queryOne();
        Adminlog::addlog(yii::$app->user->id, "查看栏目 ".$data['name']);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'data' => $data,
        ]);
    }

    /**
     * Creates a new Fenhuicat model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Fenhuicat();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $name = Yii::$app->request->post()['Fenhuicat']['name'];
            Adminlog::addlog(yii::$app->user->id, "添加分会栏目 ".$name);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    public function actionChildren($id)
    {
        $layer=Yii::$app->request->get()['layer'];
        $children = Fenhuicat::find()->where(['parent_id'=>$id])->all();
        if($children) {
            foreach($children as $k => $v) {
                $haschildren = Fenhuicat::find()->where(['parent_id'=>$v['id']])->count();
                $str = (fenhuicat::isDel($v['id'])) ? "该栏目下有子栏目或者有内容,不能删除！" : "你确定要删除该栏目吗？";
                $fd=$v['fg_id'];
                $fg = Fenhuigrade::find()->where(['id'=>$fd])->One();
                $result[$k] = array(
                    'haschildren' => $haschildren,
                    'id'          => $v['id'],
                    'parent_id'   => $v['parent_id'],
                    'name'        => $v['name'],
                    'status'      => $v['status'],
                    'url'         => $v['url'],
                    'sort'        => $v['sort'],
                    'keywords'    => $v['seo_keywords'],
                    'contents'    => $v['seo_contents'],
                    'fg_id'    => $fg['name'],
                    'deltrue'     => $str,
                    'layer'       => $layer+1,
                    'view_url'    =>  \yii\helpers\Url::to(['fenhuicat/view','id'=>$v['id']],true),
                    'update_url'  =>  \yii\helpers\Url::to(['fenhuicat/update','id'=>$v['id']],true),
                    'delete_url'  =>  \yii\helpers\Url::to(['fenhuicat/delete','id'=>$v['id']],true),
                );
            }
        } else {
            $result = array();
        }
        exit(json_encode($result));
    }
    public function actionGetchildren($id)
    {
        $result = Fenhuicat::get($id, Fenhuicat::find()->all());

        exit(json_encode($result));
    }
    /**
     * Updates an existing Fenhuicat model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {


            Adminlog::addlog(yii::$app->user->id, "修改分会栏目 ".$model->name);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Fenhuicat model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        Adminlog::addlog(yii::$app->user->id, "删除分会栏目 ".$model->name);
        $model->delete();

        return $this->redirect(['index']);
    }
    /**
     * 分会循环特定分会的栏目
     */
    public function actionGetfc($id){
        $data=Fenhuicat::find()->where(['fg_id'=>$id])->all();
        $parent = ArrayHelper::merge([0 =>'顶级分类'], ArrayHelper::map(Fenhuicat::get(0,$data), 'id', 'str_label'));
//        print_r($parent);exit;
       foreach($parent as $key=>$val){
//           print_r($val);exit;
           echo Html::tag('option', Html::encode($val), array('value' => $key));
       }
    }


    /**
     * Finds the Fenhuicat model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Fenhuicat the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
//    protected function getTree($data, $pId)
//    {
//        $html = '';
//        foreach($data as $k => $v)
//        {
//            if($v['parent_id'] == $pId)
//            { //父亲找到儿子
//                $html .= "<li>".$v['name'];
//                $html .= getTree($data, $v['id']);
//                $html = $html."</li>";
//            }
//        }
//        return $html ? '<ul>'.$html.'</ul>' : $html ;
//    }
    protected function findModel($id)
    {
        if (($model = Fenhuicat::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
